package com.rabbit.mq.producer;

import jakarta.annotation.Resource;
import org.springframework.amqp.core.*;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import java.util.Map;

/****************************************
 * 作者：HuMaSiYuan
 * 邮箱：siyueguoji@163.com
 * 日期：2023/10/12 10:48
 * 功能描述：
 ****************************************/
@Component
public class ApiCreditProducer {

    @Resource
    private AmqpTemplate rabbitTemplate;

    public void creditBank(Map<String, Object> head, String msg){
        System.out.println(MessageFormat.format("credit.bank send message: [{0}]",msg));
        rabbitTemplate.convertAndSend("creditBankExchange", "credit.bank", getMessage(head, msg));
    }

    public void creditFinance(Map<String, Object> head, String msg){
        System.out.println(MessageFormat.format("credit.finance send message:[{0}] ",msg));
        rabbitTemplate.convertAndSend("creditFinanceExchange", "credit.finance", getMessage(head, msg));
    }

    private Message getMessage(Map<String, Object> head, String msg) {

        MessageProperties messageProperties = MessagePropertiesBuilder.newInstance()
                .setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN)
                .setContentEncoding("utf-8")
                .build();

        for (Map.Entry<String, Object> entry : head.entrySet()) {
            messageProperties.setHeader(entry.getKey(), entry.getValue());
        }

        Message message = MessageBuilder.withBody(msg.getBytes(StandardCharsets.UTF_8)).andProperties(messageProperties).build();
        return message;
    }
}
